<?php
/**
 * Created by PhpStorm.
 * User: poptser@foxmail.com
 * Date: 2018/1/25
 * Time: 15:58
 */

namespace App\Http\Controllers\SortingWeb;

use App\Http\Controllers\ApiController;
use App\Services\Sorting\RefundService;
use App\Services\SortingWeb\OrderService as SortingOrder;
use App\Services\SortingWeb\ToolService;
use Illuminate\Http\Request;
use App\Services\Orders\OrderService as Order;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class SortingWebController extends ApiController {


    public $OrderService;
    public $Order;
    public $refundService;

    public $userId;

    public function __construct(SortingOrder $orderService,Order $order,
                                RefundService $refundService)
    {
        $isLogion = Auth::guard('sorting')->check();
        if(!$isLogion){
            //return $this->failed("api_token 不存在或已过期");
            header('Access-Control-Allow-Origin:*');
            header('Content-Type:application/json');
            $data['status'] = "error";
            $data['code'] = 400;
            $data['message'] = "api_token 不存在或已过期";
            echo json_encode($data);
            exit;
        }
        $this->userId = Auth::guard('sorting')->id();

        $this->OrderService = $orderService;
        $this->Order = $order;
        $this->refundService = $refundService;

    }

    /**
     * 获取主要的基本信息 配送划区 配送时间 仓库列表
     * @return mixed
     */
    public function getBaseData(){
        $return_data = null;
        $ToolService = new ToolService();
        $return_data['area'] = $ToolService->getAllDeliveryArea();
        $return_data['time'] = $ToolService->getDeliverTime();
        $return_data['warehouse'] = $ToolService->getWarehouse();
        $return_data['refund_work_type'] = $ToolService->getRefundWorkType();
        if($return_data){
            //return $allDeliveryArea;
            return $this->success($return_data,'success');
        }else{
            return $this->success(null,'未找到');
        }
    }


    /**
     * 未生成拣货单的订单列表
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getOrderPending(Request $request){
        if(empty($request->page)){
            $request->page = 1;
        }

        if(empty($request->sorting_date)){
            $request->sorting_date = "2017-12-13";
        }
        if(!is_numeric($request->sorting_order_type)){
            $request->sorting_order_type = false;
        }
        $orderData =  $this->OrderService->getOrderPending(
            $request->sorting_area,         //区域ID 0 为全部
            $request->sorting_time,         //配送时间ID 0 为全部
            $request->company_id,            //公司ID
            $request->sorting_order_type,   //订单类型 1 超时免单 0普通
            $request->sorting_date,   //配送时间
            $request->wid   //所属仓库
        );
        if($orderData){
            return $this->success($orderData,'success');
        }else{
            return $this->success(null,'未找到数据');
        }
        //echo json_encode($orderData);
    }


    /**
     * 获取拣货单包含最大订单数
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getSortingMaxNum(Request $request){
        $ToolService = new ToolService();
        $return_data = $ToolService->getSortingMaxNum($request->wid);
        if($return_data){
            return $this->success($return_data,'success');
        }else{
            return $this->success(null,'配置有误');
        }
    }

    /**
     * 设置单个拣货单最大订单数
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function setSortingMaxNum(Request $request){
        $ToolService = new ToolService();
        $return_data = $ToolService->setSortingMaxNum($request->max_num,$request->wid);
        if($return_data){
            return $this->success(null,'success');
        }else{
            return $this->success(null,'配置有误');
        }
    }


    /**
     * 生成拣货单
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function generateSortingOrder(Request $request){
        return $this->failedReturn('此功能已暂停使用');
        $order_list = explode(",",$request->order_id_list);
        $orderData =  $this->OrderService->generateSortingOrder($order_list,
            $request->wid,$request->company_id,$request->area_id,
            $request->best_time,$request->best_date,$this->userId);
        //return $orderData;
        if($orderData){
            return $this->success($orderData,'success');
        }else{
            return $this->success(null,'失败了');
        }
    }
    /**
     * 拣货单列表
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getSortingList(Request $request){
        if(empty($request->page)){
            $request->page = 1;
        }
        if(empty($request->sorting_date)){
            $request->sorting_date = date('Y-m-d',gm_time());
        }
        if(empty($request->company_id)){
            $request->company_id = false;
        }
        $orderData =  $this->OrderService->getSortingList(
            $request->sorting_area,         //区域ID 0 为全部
            $request->company_id,            //公司ID
            $request->sorting_date,   //配送时间
            $request->wid,   //所属仓库
            $request->sorting_status         //区域ID 0 为全部
        );
        if($orderData){
            return $this->success($orderData,'success');
        }else{
            return $this->success(null,'未找到数据');
        }
    }

    /**
     * 获取正常订单列表
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getNormalOrder(Request $request){
        if(empty($request->page)){
            $request->page = 1;
        }
        if(empty($request->start_date)){
            $request->start_date = date('Y-m-d',gm_time()-604800);
            $request->end_date = date('Y-m-d',gm_time());
        }
        $orderData =  $this->OrderService->getNormalOrder(
            $request->start_date,         //区域ID 0 为全部
            $request->end_date,            //公司ID
            $request->order_sn,            //配送时间
            $request->wid   //所属仓库
        );
        if($orderData){
            return $this->success($orderData,'success');
        }else{
            return $this->success(null,'未找到数据');
        }
    }

    /**
     * 获取订单延迟所需参数
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getDelayOrderInfo(Request $request){
        $orderId = $request->order_id;
        $orderData =  $this->OrderService->getDelayOrderInfo($orderId);
        if($orderData){
            return $this->success($orderData,'success');
        }else{
            return $this->success(null,'未找到数据');
        }
    }

    /**
     * 延迟订单
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function setOrderDelay(Request $request){
        $delayDate = $request->delay_date;//配送日期
        $delayTime = $request->delay_time;//配送时间
        $delayReason = $request->delay_reason;//延迟原因
        $delayRemark = $request->delay_remark;//延迟备注
        $unSorting = $request->unSorting;//解包（解除配货）

        $delay_time_array = explode("-",$delayTime);
        $startTime = $delayDate." ".$delay_time_array[0];
        $endTime = $delayDate." ".$delay_time_array[1];


        if(time()>strtotime($startTime)){
            return $this->success(null,"配送时间不能往前延迟");
        }

        $updateOrder =  $this->OrderService->setOrderBestTime($request->order_id,
            $startTime,$endTime,$unSorting);

        if($unSorting==1){
            //延迟订单，移出拣货单
            $this->OrderService->removeSortingOrder($request->order_id);
            $unSortingMsg = "已解包";
        }else{
            $unSortingMsg = "";
        }

        if($updateOrder){

            //已修改besttime 写入日志
            $ToolService = new ToolService();
            $orderStatus = $this->OrderService->getOrderStatus($request->order_id);
            $data['order_status'] = $orderStatus->order_status;
            $data['shipping_status'] = $orderStatus->shipping_status;
            $data['pay_status'] = $orderStatus->pay_status;
            $data['action_user'] = $ToolService->getNameById($request->userId);
            $data['order_id']=$request->order_id;
            $data['action_note']="已延迟订单至：".$delayDate." ".$delayTime."<br/>".
                $delayReason."//".$unSortingMsg."//".$delayRemark." [ SortingWeb ]";
            $data['log_time']=gm_time();
            $data['user_id']=$request->userId;
            $this->Order->addOrderAction($data);

            return $this->success(null,'success');
        }else{
            return $this->success(null,'失败了');
        }
    }

    /**
     * 获取商品列表
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getOrderGoods(Request $request){
        $orderGoods =  $this->OrderService->getOrderGoods($request->order_id,$request->goods_type);
        if($orderGoods){
            $data['goodsList'] = $orderGoods;
            $orderFeeInfo = $this->OrderService->judgmentOrderFee($request->order_id);
            if($orderFeeInfo->is_refund_freight==0){
                $data['orderFee'] = $orderFeeInfo->shipping_fee;
            }else{
                $data['orderFee'] = 0;
            }

            $data['orderRemark'] = $orderFeeInfo->postscript;
            $data['qualityStatus'] = $orderFeeInfo->quality_id;
            return $this->success($data,'success');
        }else{
            return $this->success(null,'失败了');
        }
    }

    public function getQuestionOrder(Request $request){
        if(empty($request->page)){
            $request->page = 1;
        }
        if(empty($request->start_date)){
            $request->start_date = date('Y-m-d',gm_time()-604800);
            $request->end_date = date('Y-m-d',gm_time());
        }
        if(empty($request->question_type)){
            $request->question_type = 0;
        }
        $orderData =  $this->OrderService->getQuestionOrder(
            $request->start_date,         //区域ID 0 为全部
            $request->end_date,            //公司ID
            $request->question_type,       //问题类型
            $request->order_sn,            //配送时间
            $request->wid
        );
        if($orderData){
            return $this->success($orderData);
        }else{
            return $this->success(null,'未找到数据');
        }
    }

    /**
     * 退货处理
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function setRefundGoods(Request $request){
        //return $request;
        $goodsList = json_decode($request->goods_list,true);
        if($request->shippingFee=="true"){
            $shippingFee = true;
        }else{
            $shippingFee = false;
        }

        if($request->refundTypeClass==1){
            //问题单商品，重组
            $goodsList = $this->refundService->buildGoodsList($goodsList);
            foreach ($goodsList as $goodsListType){
                $refundStatus = $this->refundService->refundGoods($request->order_id,$goodsListType['goodsList'],
                    $goodsListType['refundType'],$shippingFee,$request->remark,$request->userId,$request->wid,
                    $request->refundTypeClass,$request->work_type);
                $shippingFee = false;   //第二次循环，直接关闭运费处理
            }
        }else{
            //普通订单，直接处理
            $refundStatus = $this->refundService->refundGoods($request->order_id,$goodsList,
                $request->refund_type,$shippingFee,$request->remark,$request->userId,$request->wid,
                $request->refundTypeClass,$request->work_type);
        }

        if($request->refundTypeClass==1){
            //问题单处理
            //$this->OrderService->removeSortingOrder($request->order_id);
        }
        //return $refundStatus;

        if($refundStatus===true){
            return $this->success(null);
        }else{
            return $this->success(null,$refundStatus);
        }
    }

    /**
     * 获取配送列表
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getCompanyList(Request $request){
        $companyList = $this->OrderService->getCompanyList($request->wid,$request->date);
        if($companyList){
            return $this->success($companyList);
        }else{
            return $this->success(null);
        }
    }

    /**
     * 获取配送时间列表
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getTimeList(Request $request){
        $timeList = $this->OrderService->getTimeList($request->wid,$request->date,
            $request->company_id);
        if($timeList){
            return $this->success($timeList);
        }else{
            return $this->success(null);
        }
    }

    /**
     * 获取区域列表
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getAreaList(Request $request){
        $best_time = explode("-",$request->time);
        $timeList = $this->OrderService->getAreaList($request->wid,$request->date,
            $request->company_id,$best_time[0],$best_time[1]);
        if($timeList){
            return $this->success($timeList);
        }else{
            return $this->success(null);
        }
    }


    /**
     * 跳过问题单
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function jumpQuestionOrder(Request $request){
        $orderId = $request->order_id;
        $userId = $request->userId;
        $remark = $request->remark;
        $setRe = $this->OrderService->setOrderNorm($orderId);
        if($setRe !=0){
            $ToolService = new ToolService();
            $orderStatus = $this->OrderService->getOrderStatus($orderId);
            $dataAction['order_status'] = $orderStatus->order_status;
            $dataAction['shipping_status'] = $orderStatus->shipping_status;
            $dataAction['pay_status'] = $orderStatus->pay_status;
            $dataAction['action_user'] = $ToolService->getNameById($userId);
            $dataAction['order_id']=$orderId;
            $dataAction['action_note']='确认取消问题单:'.$remark." [ SortingWeb ]";;
            $dataAction['log_time']=gm_time();
            $dataAction['user_id']=$userId;
            $this->Order->addOrderAction($dataAction);
            return $this->success(null);
        }else{
            return $this->failed("设置错误");
        }
    }

}